<template>
  <WidgetContainer :widget-id="config.id">
    <template #bottom>
      <div class="heard-box">
        <el-button type="primary" @click.stop="addColumn" :icon="Plus" circle size="small" />
        <el-button type="info" @click.stop="delColumn" :icon="Minus" circle size="small" />
      </div>
    </template>

    <el-table :data="tableData" stripe class="table-container" :class="config.attributes?.cssClass" :border="config.attributes.border" v-show="!config.attributes.hidden"
      :stripe="config.attributes.stripe" :fit="config.attributes.fit" :max-height="config.attributes.maxHeight">
      <el-table-column v-for="(column, index) in config.children" :key="column.id"
        :label="getColumnInfo(column, 'label', '未命名')" :width="getColumnInfo(column, 'width', 'auto')"
        :align="getColumnInfo(column, 'columnAlign', 'left')" :fixed="getColumnInfo(column, 'columnFixed', false)">
        <template #default="{ $index }">
          <draggable v-model="column.children"
            :group="{ name: 'form', pull: 'clone', put: (to, from, dragged) => canDrop(from, column.children) }"
            :animation="150" :sort="false" item-key="id" @add="onFieldDrop(index)" class="col-draggable">
            <template #item="{ element: child }">
              <component :is="designer.renderComponent(child)" :row-index="$index" :parent-id="config.id" :config="child" />
            </template>
          </draggable>
        </template>
      </el-table-column>
    </el-table>
  </WidgetContainer>
</template>

<script setup>
import { inject, onMounted, ref } from 'vue';
import { Plus, Minus } from '@element-plus/icons-vue';
import { executeEventHandler } from '@/utils/eventExecutor'
import { ElMessage } from 'element-plus'

const formData = inject('formData')
const widgetList = inject('widgetList')

const designer = inject('designer');
const selectWidgetId = inject('selectWidgetId')

const props = defineProps({
  config: {
    type: Object,
    required: true,
    default: () => ({ children: [] }),
  },
});

const tableData = ref([]); // 静态展示用，后续支持行数据编辑可扩展

const getColumnInfo = (column, field, none) => {
  if (column.children && column.children.length != 0 && column.children[0].attributes && column.children[0].attributes[field]) {
    return column.children[0].attributes[field];
  } else {
    return none;
  }
}

// 添加一个空列
const addColumn = () => {
  props.config.children.push({
    type: 'column',
    label: '子表列',
    id: designer.generateUniqueId('column',widgetList.value),
    children: [],
  });
};

// 删除最后一列
const delColumn = () => {
  if (props.config.children.length > 0) {
    props.config.children.pop();
  }
};

// 判断是否允许拖入
const canDrop = (from, children) => {
  //return from?.options?.isFormItem === true && children.length == 0;
  return children.length == 0;
};

// 拖入组件后设置列配置
const onFieldDrop = (columnIndex) => {
  const column = props.config.children[columnIndex];
  if (!column) return;
  const dropped = column.children?.[0];
  if (dropped && dropped.attributes?.label && dropped?.isFormItem ) {
    selectWidgetId.value = dropped.id
    dropped['subFormId'] = props.config.id// 对应子表单id
    dropped.attributes.showLabel = false// 不显示标签
    dropped.attributes['columnAlign'] = 'left'//添加对齐方式属性
    dropped.attributes['columnFixed'] = false//添加列固定属性
  } else if(dropped) {
    column.children?.splice(0,column.children.length)
    ElMessage.warning('该组件只允许拖入表单组件到单元格！')
  }
};

// 初始挂载添加三个空列（仅首次）
onMounted(() => {
  formData.value[props.config.id] = [{}]
  tableData.value = formData.value[props.config.id]
  if (props.config.children.length === 0) {
    addColumn();
    addColumn();
    addColumn();
  } else {
    executeEventHandler(props.config.events?.onMounted, { widgetConfig: props.config, formData: formData.value, widgetList: widgetList.value })
  }
});
</script>

<style scoped>
.heard-box {
  margin-top: 3px;
  display: flex;
  gap: 6px;
  justify-content: flex-end;
}

.table-container {
  width: 100%;
  margin: 5px 0;
}

.col-draggable {
  min-height: 50px;
}
</style>